<template>
  <div class="donor-page">
    <!-- 标题 -->
    <p class="title">
      <i class="el-icon-user-solid"></i> 捐赠人信息
    </p>
    <el-divider></el-divider>

    <!-- 搜索表单 和 添加按钮 -->
    <el-form :inline="true" :model="searchForm" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="searchForm.donorId" placeholder="输入捐赠者 ID"></el-input>
      </el-form-item>
      <el-form-item label>
        <el-input size="small" v-model="searchForm.donorName" placeholder="输入捐赠者姓名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addRow">添加</el-button>
        <el-button size="small" icon="el-icon-close" v-show="isSearch" @click="exitSearch">退出搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 捐赠人表格 -->
    <el-table :data="donorData" border highlight-current-row>
      <el-table-column prop="donorId" label="捐赠者 ID"></el-table-column>
      <el-table-column prop="donorName" label="捐赠者姓名"></el-table-column>
      <el-table-column prop="phoneNumber" label="电话号码"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column prop="email" label="电子邮箱"></el-table-column>
      <el-table-column label="物资捐赠情况" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="info" @click="findSupplies(scope.row.donorId)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row.donorId)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页栏 -->
    <el-pagination
      background
      :total="totalRow"
      :current-page="currentPage"
      :page-sizes="[15, 30, 50, 100]"
      :page-size="pageSize"
      @current-change="currentChange"
      @size-change="sizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <!-- 编辑表单 -->
    <el-dialog title="编辑" :visible.sync="editFormVisible">
      <el-form ref="newRow" :model="newRow" :rules="rules" label-width="100px">
        <el-form-item prop="donorId" label="捐赠者 ID">
          <el-input v-model="newRow.donorId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item prop="donorName" label="捐赠者姓名">
          <el-input v-model="newRow.donorName"></el-input>
        </el-form-item>
        <el-form-item prop="phoneNumber" label="电话号码">
          <el-input v-model="newRow.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item prop="address" label="地址">
          <el-input v-model="newRow.address"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="电子邮箱">
          <el-input v-model="newRow.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditedRow('newRow')">确定</el-button>
      </span>
    </el-dialog>

    <!-- 添加表单（和编辑表单基本相同） -->
    <el-dialog title="添加新的条目" :visible.sync="addFormVisible">
      <el-form ref="newRow" :model="newRow" :rules="rules" label-width="100px">
        <el-form-item prop="donorId" label="捐赠者 ID">
          <el-input v-model="newRow.donorId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item prop="donorName" label="捐赠者姓名">
          <el-input v-model="newRow.donorName"></el-input>
        </el-form-item>
        <el-form-item prop="phoneNumber" label="电话号码">
          <el-input v-model="newRow.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item prop="address" label="地址">
          <el-input v-model="newRow.address"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="电子邮箱">
          <el-input v-model="newRow.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitNewRow('newRow')">确定</el-button>
      </span>
    </el-dialog>

    <!-- 查看某单位的捐赠情况 -->
    <el-dialog title="查看捐赠情况" :visible.sync="receiptTableVisible">
      <el-table :data="receiptTableData">
        <el-table-column prop="receiptId" label="物资 ID"></el-table-column>
        <el-table-column prop="donorId" label="捐赠者 ID"></el-table-column>
        <el-table-column prop="suppliesName" label="物资名称"></el-table-column>
        <el-table-column prop="type" label="种类"></el-table-column>
        <el-table-column prop="specifications" label="规格"></el-table-column>
        <el-table-column prop="units" label="单位"></el-table-column>
        <el-table-column prop="number" label="数量"></el-table-column>
        <el-table-column prop="donateTime" label="捐赠时间"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      donorData: [
        {
          donorId: "",
          donorName: "",
          phoneNumber: "",
          address: "",
          email: "",
        },
      ],
      searchForm: {
        donorId: "",
        donorName: "",
      },
      totalRow: 100,
      currentPage: 1,
      pageSize: 15,
      newRow: {
        donorId: "",
        donorName: "",
        phoneNumber: "",
        address: "",
        email: "",
      },
      rules: {
        phoneNumber: [{ required: true, message: "电话号码为必填项" }],
        email: [
          { required: true, message: "电子邮箱为必填项" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
        ],
      },
      receiptTableData: [
        {
          receiptId: "",
          donorId: "",
          suppliesName: "",
          type: "",
          specifications: "",
          units: "",
          number: "",
          donateTime: "",
        },
      ],
      editFormVisible: false,
      addFormVisible: false,
      receiptTableVisible: false,
      isSearch: false,
    };
  },
  computed: {
    totalPage() {
      return Math.ceil(this.totalRow / this.pageSize);
    },
  },
  methods: {
    // [GET] 通过 当前页 和 每页显示的条数 更新表格信息
    getData(currentPage, pageSize) {
      this.axios
        .get("/donor", {
          params: {
            currentPage: currentPage,
            pageSize: pageSize,
          },
        })
        .then((response) => {
          if (response.status === 200) {
            console.log("donorData: " + response.data);
            // 更新当前表格信息
            this.donorData = response.data;
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },

    // [GET] 通过 捐赠者ID 和 捐赠者姓名 查找指定行
    search() {
      if (this.searchForm.donorId === "" && this.searchForm.donorName === "") {
        return false;
      }
      this.axios
        .get("/donor/search", {
          params: {
            donorId: this.searchForm.donorId,
            donorName: this.searchForm.donorName,
          },
        })
        .then((response) => {
          if (response.status === 200) {
            this.isSearch = true;
            this.totalRow = response.data.totalRow;
            this.currentPage = 1;
            // 使用搜索结果更新表格
            this.getData(this.currentPage, this.pageSize);
          }
          // console.log(response);
        })
        .catch(() => {
          this.$message({
            message: "搜索失败",
            type: "error",
          });
        });
    },

    // 编辑按钮事件，初始化newRow，弹出编辑表单
    handleEdit(index, row) {
      Object.getOwnPropertyNames(this.newRow).forEach((key) => {
        this.newRow[key] = row[key];
      });
      this.editFormVisible = true;
    },

    // [PUT] 提交newRow，编辑条目，更新表格信息
    submitEditedRow(formName) {
      // console.log(this.newRow);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.axios
            .put("/donor/edit", JSON.stringify(this.newRow))
            .then((response) => {
              // console.log(response);
              if (response.status === 200) {
                this.getData(this.currentPage, this.pageSize); // 更新表格信息
                this.editFormVisible = false;
                this.$message({
                  message: "更新成功",
                  type: "success",
                });
              }
            })
            .catch(() => {
              this.$message({
                message: "更新失败",
                type: "error",
              });
            });
        } else {
          return false;
        }
      });
    },

    // [delete] 删除表格中的一行信息
    handleDelete(index, id) {
      console.log(index, id);
      this.$confirm("确定删除该行？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.axios
          .delete("/donor/delete", {
            params: {
              donorId: id,
            },
          })
          .then((response) => {
            if (response.status === 200) {
              this.totalRow--;
              if (this.totalRow < this.currentPage * this.pageSize) {
                this.currentPage--;
              }
              this.getData(this.currentPage, this.pageSize); // 更新表格信息
              this.$message({
                message: "删除成功",
                type: "success",
              });
            }
            // console.log(response);
          })
          .catch((error) => {
            this.$message({
              message: "删除失败",
              type: "error",
            });
            console.error(error);
          });
      })
      .catch(() => {
        return false;
      });
    },

    // 处理添加按钮，弹出添加信息表单
    addRow() {
      // 清空newRow
      Object.getOwnPropertyNames(this.newRow).forEach((key) => {
        this.newRow[key] = "";
      });
      this.addFormVisible = true;
    },

    // [POST] 提交newRow，添加新的条目，更新表格信息
    submitNewRow(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.axios
            .post("/donor/add", JSON.stringify(this.newRow))
            .then((response) => {
              if (response.status === 200) {
                this.totalRow++;
                console.log(this.totalRow);
                this.getData(this.currentPage, this.pageSize); // 更新表格信息
                this.addFormVisible = false;
                this.$message({
                  message: "更新成功",
                  type: "success",
                });
              }
              // console.log(response);
            })
            .catch(() => {
              this.$message({
                message: "更新失败",
                type: "error",
              });
            });
        } else {
          return false;
        }
      });
    },

    // 处理用户翻页
    currentChange(val) {
      this.currentPage = val;
      this.getData(this.currentPage, this.pageSize);
    },

    // 处理每页显示总条数的变化
    sizeChange(val) {
      this.pageSize = val;
      this.getData(this.currentPage, this.pageSize);
    },

    // [GET] 传递捐赠人ID 获取该捐赠人的捐赠记录
    findSupplies(donorId) {
      this.axios
        .get("/receipt/donor", {
          params: {
            donorId: donorId,
          },
        })
        .then((response) => {
          if (response.status === 200) {
            this.receiptTableData = response.data;
            this.receiptTableVisible = true;
          }
        })
        .catch((error) => {
          console.error(error);
          this.$message({
            message: "查看失败",
            type: "error",
          });
        });
    },

    exitSearch() {
      this.isSearch = false;
      this.searchForm.donorId = "";
      this.searchForm.donorName = "";
      this.axios
        .get("/donor/total")
        .then((response) => {
          if (response.status === 200) {
            this.totalRow = response.data.totalRow;
          }
        })
        .catch((error) => {
          console.error(error);
        });
      this.getData(this.currentPage, this.pageSize);
    },
  },

  created() {
    this.axios
      .get("/donor/total")
      .then((response) => {
        if (response.status === 200) {
          this.totalRow = response.data.totalRow;
        }
      })
      .catch((error) => {
        console.error(error);
      });
    this.getData(this.currentPage, this.pageSize);
  },
};
</script>

<style scoped>
.donor-page {
  text-align: left;
}

.title {
  margin: 5px 0 0 15px;
}

.user-search {
  padding-left: 15px;
}

.el-pagination {
  margin-top: 20px;
  margin-bottom: 30px;
}

.el-dialog__body {
  padding-right: 100px !important;
  padding-left: 50px !important;
}

.el-dialog__footer {
  padding: 0 100px 30px 30px !important;
}
</style>